package models;

import play.*;
import play.db.jpa.*;

import javax.persistence.*;
import java.util.*;

@Entity
public class Vote extends Model {
	
	@ManyToOne
    public User castedBy;
    
	@ManyToOne
    public Lecture lecture;
    
	@ManyToOne
    public Answer answer;
    
    public boolean positive;
    
    public Vote (User castedBy, Lecture lecture, boolean positive) {
    	this.castedBy = castedBy;
    	this.lecture = lecture;
    	this.positive = positive;
    	create();
    }
    
    public Vote (User castedBy, Answer answer, boolean positive) {
    	this.castedBy = castedBy;
    	this.answer = answer;
    	this.positive = positive;
    	create();
    }
    
    //Get votes for a specific lecture
    public static List<Vote> getVotes(Lecture lecture) {
    	return Vote.find("lecture = ?", lecture).fetch();
    }
    
    //Get votes for a specific answer
    public static List<Vote> getVotes(Answer answer) {
    	return Vote.find("answer = ?", answer).fetch();
    }
    
    //Get votes for a specific user
    public static List<Vote> getVotes(User user) {
    	return Vote.find("castedBy = ?", user).fetch();
    }
    
    //Get number of upvotes for a specific answer
    public static long getUpvoteCount(Answer answer) {
    	return Vote.count("answer = ? and positive = true", answer);
    }
    
    //Get number of downvotes for a specific answer
    public static long getDownvoteCount(Answer answer) {
    	return Vote.count("answer = ? and positive = false", answer);
    }
    
    //Check, whether a user has already voted for a lecture
    public static boolean hasVoted(User user, Lecture lecture) {
    	return Vote.find("castedBy = ? and lecture = ?", user, lecture).first() != null;
    }
    
    //Ceck, whether a user has already voted for an answer
    public static boolean hasVoted(User user, Answer answer) {
    	return Vote.find("castedBy = ? and answer = ?", user, answer).first() != null;
    }
    
    //Get a vote of a specific user for a lecture
    public static Vote getVote(User user, Lecture lecture) {
    	return Vote.find("castedBy = ? and lecture = ?", user, lecture).first();
    }
    
  //Get a vote of a specific user for an answer
    public static Vote getVote(User user, Answer answer) {
    	return Vote.find("castedBy = ? and answer = ?", user, answer).first();
    }
}
